package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.CryptoUtil;
import com.zhongkai.app.service.AppUserService;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.*;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * APP用户
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AppUserServiceImpl implements AppUserService {

    @Autowired
    private IBaseDao iBaseDao;


    @Autowired
    private PageQuerDao pageQuerDao;

    /**
     * APP用户添加
     *
     * @param uuid     唯一标识
     * @param name     名字
     * @param phone    手机号
     * @param password 密码
     * @param address  详细地址
     * @param province 省
     * @param city     市
     * @param country  区
     * @param sex      性别 1 男 2女
     */
    @Override
    public ZhongkaiResult addUser(String uuid, String name, String phone, String password, String address, String province, String city, String country, String sex) throws Exception{

        if (StringUtils.isNullOrEmpty(name) || StringUtils.isNullOrEmpty(phone)
                || StringUtils.isNullOrEmpty(password) || StringUtils.isNullOrEmpty(address)
                || StringUtils.isNullOrEmpty(province) || StringUtils.isNullOrEmpty(city)
                || StringUtils.isNullOrEmpty(country) || StringUtils.isNullOrEmpty(sex)
                ) {
            return ZhongkaiResult.build(400, "数据不完整,注册失败");
        }


        //    || role == 0    添加详细地址
        AppUser appUser = (AppUser) iBaseDao.get("from AppUser au where au.appPhone='" + phone + "'");

        if (appUser != null) {
            return ZhongkaiResult.build(499, "此用户已存在");
        }

        appUser = new AppUser();


/*        Long aLong = pageQuerDao.pageMax(appUser) + 1;
        appUser.setId(aLong);*/
        appUser.setAppUuid(uuid);
        appUser.setAppName(name);
        appUser.setAppPhone(phone);

        //加密
        String pass = CryptoUtil.encode64(CryptoUtil.SALT, password);

        //设置加密后的密码
        appUser.setAppPassword(pass);


        appUser.setAppAddress(address);
        appUser.setAppProvince(province);
        appUser.setAppCity(city);
        appUser.setAppCountry(country);


        appUser.setAppSex(sex);

/*        role=1; //暂时全部为普通用户
        AppRole appRole = (AppRole) iBaseDao.get("from AppRole ar where ar.id='" + role + "'");
        if (appRole == null) {
            return ZhongkaiResult.build(400, "此角色不存在");
        }*/

        appUser.setAppImg("http://111.61.64.62:8001/group1/M00/00/01/wKgZhV3krh2AaPVDAAQqKpbszHg957.jpg");
        appUser.setAppSex(sex);
        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        appUser.setAppTime(millis);
        appUser.setAppRemove("1");
        appUser.setAppVice("普通用户"); //设置权限
        appUser.setAppViceId(1); //设置权限 普通用户


//---------------------------------------------------------------------
        Province province1 = (Province) iBaseDao.get("from Province pr where pr.provinceId='" + province + "'");

        City city1 = (City) iBaseDao.get("from City pr where pr.cityId='" + city + "'");

        Country country1 = (Country) iBaseDao.get("from Country pr where pr.countryId='" + country + "'");

        if (province1 == null || city1 == null || country1 == null) {
            return ZhongkaiResult.build(500, "该地区不存在,请重新选择");
        }

        String address_all = province1.getName() + city1.getName() + country1.getName() + address;

        appUser.setAddress_all(address_all);


        iBaseDao.save(appUser);

        return ZhongkaiResult.build(200, "添加成功");

        //arRelation.s
    }


    /**
     * APP用户修改
     *
     * @param id       唯一标识
     * @param name     名字
     * @param phone    手机号
     * @param password 密码
     * @param address  详细地址
     * @param province 省
     * @param city     市
     * @param country  区
     * @param sex      性别
     */
    @Override
    public ZhongkaiResult updateUser(Long id, String name, String phone, String password, String address, String province, String city, String country, String sex) {
        if (StringUtils.isNullOrEmpty(name) || StringUtils.isNullOrEmpty(phone)
                || StringUtils.isNullOrEmpty(password) || StringUtils.isNullOrEmpty(address)
                || StringUtils.isNullOrEmpty(province) || StringUtils.isNullOrEmpty(city)
                || StringUtils.isNullOrEmpty(country) || StringUtils.isNullOrEmpty(sex)
                || id == 0
                ) {

            return ZhongkaiResult.build(400, "数据不完整");
        }
        AppUser appUser = (AppUser) iBaseDao.get("from AppUser au where au.id='" + id + "'");

        if (appUser == null) {
            return ZhongkaiResult.build(501, "此用户不存在");
        }

        if (!phone.equals(appUser.getAppPhone())) {
            AppUser app_phoen = (AppUser) iBaseDao.get("from AppUser au where au.appPhone='" + phone + "'");
            if (app_phoen != null) {
/*                app_phoen.setAppPhone("null");
                iBaseDao.update(app_phoen);*/

                return ZhongkaiResult.build(501, "您修改的手机号已注册,如有疑问请联系管理员");
            }
        }

        appUser.setAppName(name);
        appUser.setAppPhone(phone);

        if (password.equals(appUser.getAppPassword())) {
            appUser.setAppPassword(password);
        } else {
            //加密
            try {
                String pass = CryptoUtil.encode64(CryptoUtil.SALT, password);

                //设置加密后的密码
                appUser.setAppPassword(pass);
            } catch (Exception e) {
                e.printStackTrace();
                return ZhongkaiResult.build(400, "数据加密失败");
            }
        }


        appUser.setAppAddress(address);
        appUser.setAppProvince(province);
        appUser.setAppCity(city);
        appUser.setAppCountry(country);

        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        appUser.setAppMoTime(millis);
        appUser.setAppRemove("1");
        appUser.setAppSex(sex);
//......................................................................

        Province province1 = (Province) iBaseDao.get("from Province pr where pr.provinceId='" + province + "'");

        City city1 = (City) iBaseDao.get("from City pr where pr.cityId='" + city + "'");

        Country country1 = (Country) iBaseDao.get("from Country pr where pr.countryId='" + country + "'");

        if (province1 == null || city1 == null || country1 == null) {
            return ZhongkaiResult.build(500, "该地区不存在,请重新选择");
        }

        String address_all = province1.getName() + city1.getName() + country1.getName() + address;

        appUser.setAddress_all(address_all);


    //    SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.userUuid='" + appUser.getAppUuid() + "'");

        List<SetUnit> list2 = iBaseDao.find("from SetUnit su where su.userUuid='" + appUser.getAppUuid() + "'");

        if (list2 != null){
            if (list2.size() > 0) {
                for (SetUnit setUnit : list2) {
                    setUnit.setUserName(name);
                    setUnit.setUserPhone(phone);
                    iBaseDao.update(setUnit);
                }
            }
        }

/*
        if (setUnit != null){
            setUnit.setUserName(name);
            setUnit.setUserPhone(phone);
            iBaseDao.update(setUnit);

        }*/
        try {
            iBaseDao.update(appUser);

            return ZhongkaiResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(400, "修改失败");
        }
    }

    @Override
    public ZhongkaiResult removeUser(Long id) {
        if (id == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }
        AppUser appUser = (AppUser) iBaseDao.get("from AppUser au where au.id='" + id + "'");

        if (appUser == null) {
            return ZhongkaiResult.build(501, "此用户不存在");
        } else if ("2".equals(appUser.getAppRemove())) {
            return ZhongkaiResult.build(501, "此用户已被删除");
        }

        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.userUuid='" + appUser.getAppUuid() + "'");


        if (setUnit != null){
            return ZhongkaiResult.build(501, "此用户已绑定设备,请先解除绑定");

        }
        //FsonUser
        List<FsonUser> list = iBaseDao.find("from FsonUser su where su.appUuid='" + appUser.getAppUuid() + "'");

        if (list != null){
            if (list.size() > 0) {

                for (FsonUser fsonUser : list) {
                    iBaseDao.delete(fsonUser);
                }
            }
        }


        iBaseDao.delete(appUser);
        return ZhongkaiResult.ok();
/*        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        appUser.setAppMoTime(millis);

        appUser.setAppRemove("2");
        appUser.setAppPhone(appUser.getAppPhone()+"&");
        try {
            iBaseDao.update(appUser);
            return ZhongkaiResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(400, "删除失败");
        }*/

    }

    @Override
    public ZhongkaiResult listUser(Integer page, Integer rows) {
        if (page == 0 || rows == 0) {
            return ZhongkaiResult.build(400, "数据不完整");
        }

        try {
            PageBean pageBean = new PageBean();
            pageBean.setCurrentPage(page);
            pageBean.setPageSize(rows);
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(AppUser.class);
            detachedCriteria.add(Restrictions.eq("appRemove", "1")); //增加条件
            pageBean.setDetachedCriteria(detachedCriteria);
            pageQuerDao.pageQuery(pageBean);
            return ZhongkaiResult.ok(pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(405, "查询失败");
        }
    }
}
